package com.xmb.wpclient.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Configuration
public class RedisConfig {
	
	public ObjectMapper objectMapper() {
		ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        return mapper;
	}
	
	public Jackson2JsonRedisSerializer<?> Jackson2JsonRedisSerializer() {
		Jackson2JsonRedisSerializer<?> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper());
		return jackson2JsonRedisSerializer;
	}

	// 缓存管理器
	@Bean
	public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) {
		// 生成一个默认配置，通过config对象即可对缓存进行自定义配置
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
				// 此配置可以使redis的值不为乱码。  设置序列化后返回的是新的RedisCacheConfiguration。
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(Jackson2JsonRedisSerializer()))
				//设置默认缓存时间
				.entryTtl(Duration.ofHours(1));
		// 设置一个初始化的缓存空间set集合
        Set<String> cacheNames = new HashSet<>();
        cacheNames.add("manufacturing_default");

        // 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        // 通过Duration可以自己实现以什么时间为单位
        configMap.put("manufacturing_default", config.entryTtl(Duration.ofHours(2)));

        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory))
                .initialCacheNames(cacheNames)  
                // 注意这两句的调用顺序，一定要先调用该方法设置初始化的缓存名，再初始化相关的配置
                .withInitialCacheConfigurations(configMap)
                .cacheDefaults(config).build();
	}

	//  修改redis默认的缓存序列化策略（jdk序列化），
	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		template.setValueSerializer(Jackson2JsonRedisSerializer());
		//使用StringRedisSerializer来序列化和反序列化redis的key值
		template.setKeySerializer(new StringRedisSerializer());
		//必须执行这个函数,初始化RedisTemplate
		template.afterPropertiesSet();
		return template;

//		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
//		redisTemplate.setConnectionFactory(redisConnectionFactory);
//		FastJson2JsonRedisSerializer fastJson2JsonRedisSerializer = new FastJson2JsonRedisSerializer(Object.class);
//		ObjectMapper objectMapper = new ObjectMapper();
//		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//		fastJson2JsonRedisSerializer.setObjectMapper(objectMapper);
//
//		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//		// key采用String的序列化方式
//		redisTemplate.setKeySerializer(stringRedisSerializer);
//		// string的value采用fastJson序列化方式
//		redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer);
//		// hash的key也采用String的序列化方式
//		redisTemplate.setHashKeySerializer(stringRedisSerializer);
//		// hash的value采用fastJson序列化方式
//		redisTemplate.setHashValueSerializer(fastJson2JsonRedisSerializer);
//		redisTemplate.afterPropertiesSet();
//		return redisTemplate;
	}
	
}
